package com.ting.etp.loader.launcher.coexist;



import com.ting.etp.loader.launcher.EtpAbstractMainLauncher;
import com.ting.etp.loader.runner.EtpMethodRunner;
import com.ting.etp.loader.utils.ResourceUtils;

import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 主程序启动者
 *
 * @author starBlues
 * @since 3.0.0
 * @version 3.0.0
 */
public class EtpIsolationBaseLauncher extends EtpAbstractMainLauncher {

    private final EtpMethodRunner etpMethodRunner;

    public EtpIsolationBaseLauncher(EtpMethodRunner etpMethodRunner) {
        this.etpMethodRunner = etpMethodRunner;
    }

    @Override
    protected boolean resolveThreadClassLoader() {
        return false;
    }

    @Override
    protected ClassLoader createClassLoader(String... args) throws Exception {
        return getParentClassLoader();
//        return new GenericClassLoader(MAIN_CLASS_LOADER_NAME, getParentClassLoader(),
//                getResourceLoaderFactory(args));
    }

    @Override
    protected ClassLoader launch(ClassLoader classLoader, String... args) throws Exception {
        etpMethodRunner.run(classLoader);
        ResourceUtils.release(classLoader);
        return classLoader;
    }

//    protected ResourceLoaderFactory getResourceLoaderFactory(String... args){
//        return ResourceLoaderFactoryGetter.get(MAIN_CLASS_LOADER_NAME, args);
//    }

    protected ClassLoader getParentClassLoader(){
        return EtpIsolationBaseLauncher.class.getClassLoader();
    }

//    protected Set<URL> getBaseResource() {
//        Set<URL> urls = new HashSet<>();
//        String classPath = ManagementFactory.getRuntimeMXBean().getClassPath();
//        if(!ObjectUtils.isEmpty(classPath)){
//            String[] classPathStr = classPath.split(";");
//            for (String path : classPathStr) {
//                try {
//                    urls.add(new URL(path));
//                } catch (MalformedURLException e) {
//                    // 忽略
//                }
//            }
//        }
//        ClassLoader sourceClassLoader = Thread.currentThread().getContextClassLoader();
//        if(sourceClassLoader instanceof URLClassLoader){
//            URLClassLoader urlClassLoader = (URLClassLoader) sourceClassLoader;
//            final URL[] urLs = urlClassLoader.getURLs();
//            urls.addAll(Arrays.asList(urLs));
//        }
//        return urls;
//    }

}
